package com.gxuwz.zjh.mxbbx.controller;

import com.gxuwz.zjh.mxbbx.entity.Limit;
import com.gxuwz.zjh.mxbbx.entity.Role;
import com.gxuwz.zjh.mxbbx.entity.User;
import com.gxuwz.zjh.mxbbx.service.ILimitService;
import com.gxuwz.zjh.mxbbx.service.IRoleService;
import com.gxuwz.zjh.mxbbx.service.IUserService;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhangjiahui
 * @since 2021-03-14
 */
@Controller
public class LoginController {

    @Autowired
    private IUserService iUserService;
    @Autowired
    private IRoleService iRoleService;
    @Autowired
    private ILimitService iLimitService;

    /**
     * 默认登录界面显示
     * @return
     */
    @RequestMapping(value = "/")
    @RequestBody
    public String login() {
        return "forward:login.jsp";
    }


    /**
     * 登录判断
     * @param user
     * @param request
     * @param response
     * @return
     */
    @RequestBody
    @RequestMapping(value = "/login",method = {RequestMethod.POST})
    public ModelAndView login(ModelAndView modelAndView, User user,
                              HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if(user.getUserId() == null){
            request.setAttribute("result", "none1");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        }else if(user.getPassWord() == null | user.getPassWord() == "" ){
            request.setAttribute("result", "none2");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        }else {
            User user2 = iUserService.findUserById(user);
            if(user2 == null){
                request.setAttribute("result", "full");
                request.getRequestDispatcher("/login.jsp").forward(request, response);
            }else {
                if (user2.getPassWord().equals(user.getPassWord())) {
                    // 存放 user 到session中，用于aop和拦截器的判断！！！
                    request.getSession().setAttribute("user", user2);
                    // 根据 RoleId 查询对应id的名称
                    Role role = new Role();
                    role.setRoleId(user2.getRoleId());
                    Role role2 = iRoleService.findRoleById(role);
                    request.getSession().setAttribute("role", role2);
                    // 存放角色名称，到前端输出
                    List<Role> roles = iRoleService.findRoleAll();
                    request.getSession().setAttribute("roles", roles);
                    // 查询对应userId的权限String集合，存放到session中，用于拦截器的判断！！！。
                    System.out.println("用户：" + user.getUserId());
                    System.out.println("拥有权限名称：=========================");
                    String[] limits = role2.getRoleLimit().split(",");
                    for (int i = 0; i < limits.length; i++) {
                        System.out.print(limits[i] + ";");
                    }
                    System.out.println(" ");
                    System.out.println("=====================================");
                    // 登录成功可以设置时间更长一些
                    //setMaxInactiveInterval(60) 60S内不做任何事情，Session就失效。比如，你刚登录了系统，接着跑去财务部收钱，                  
                    // 70S后回来，再继续操作系统，这时应该会提示重新登录。
                    request.getSession().setMaxInactiveInterval(60 * 2);
                    // 保存登录状态
                    Cookie ck = new Cookie("JSESSIONID", request.getSession().getId());
                    ck.setPath("/");
                    // session最长存在时间 (暂设1小时)
                    ck.setMaxAge(60 * 60);
                    response.addCookie(ck);
                    request.getSession().setAttribute("limits", limits);
                    modelAndView.setViewName("index");
                    return modelAndView;
                }else{
                    request.setAttribute("result", "none");
                    request.getRequestDispatcher("/login.jsp").forward(request, response);
                }
            }
        }
        modelAndView.setViewName("error/notFind");
        return modelAndView;
    }


    /**
     * 默认欢迎界面
     * @return
     */
    @RequestMapping(value = "/hello")
    public String hello() {
        return "/error/hello";
    }

    /**
     * 退出登录
     * @return
     */
    @RequestMapping(value = "/loginEnd")
    public void loginEnd(HttpServletRequest request, HttpServletResponse response){
        request.getSession().invalidate();
        try {
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
